Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is my query lasting for long time or it's database connection
I'm coding in Django and I have a management command in one of my apps. This commands code is as follows : while True: # Run a query on database # Do some processing on it time.sleep(6 * 3600) # six hours sleep As you can see, in an infinite loop, every six hours, I fetch some objects from database, do some processing on them and repeat again after six hours. My database is postgresql, I'm using python3 with Django. The problem is that when I use htop on my system to monitor server status, I see that CPU time of this commands database connection is so large, as you see in picture below : and the related query in database is : My question is that, is django holding the connection to database for my command and CPU time shown is for the whole life of infinite loop, or it's the CPU usage of one of my queries in just one loop? In another words, should I care about the very low speed of my query or it's OK and time shown is for the whole time? -
problem loading a static css file with django
hi trying to load a static css file but to no avail: home.html: {% extends 'base.html' %} {% block body%} {% load static %} <link rel="stylesheet" href="{% static 'home/style.css' %}" type="text/css"> <div class="container"> <br/> <form method="post"> {% csrf_token %} {{ form.post }} <br /> <button type="submit">Submit</button> </form> <h2>{{ text }}</h2> {% for post in posts %} <h1>{{ post.post }}</h1> <p>Posted </b> on {{ post.created }}</p> {% endfor %} </div> {% endblock %} style.css: .HomeForm { size:20; } forms.py: class HomeForm(forms.ModelForm): post = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'How are you feeling?', 'size': '20', } )) I have a feeling im loading the static file in the wrong place, whats the solution thanks in advance. -
How to fetch data with ajax call in Django and Wagtail
I'm using wagtail with Python and Django. I have model as follows: class HomePage(Page): logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) banner_text = RichTextField(blank=True) def get_context(self, request): context = super().get_context(request) context['vehicles'] = get_vehicles("nl")[0:12] return context content_panels = Page.content_panels + [ FieldRowPanel([ImageChooserPanel('logo', classname="col4")]classname="full"), FieldRowPanel([FieldPanel('banner_text', classname="full") classname="full") ] And get_vehicles("nl") is as follows: def get_vehicles(lang): response = requests.get(API_URL, headers={'Authorization': "Token {}".format(token), "Accept-Language": lang}) data = json.loads(response.content.decode("utf-8")) return data['vehicles'] Is there any way to do get those vehicles with ajax call inside def get_context(self, request):? I want to show some spinner in my home_page.html template until all vehicles are fetched. I'm totally new to wagtail and I'm not sure how can I do that. -
django-admin-sortable not saving order of the existing objects
I use django-admin-sortable 2.1.2 and django 1.11. The problem is that the order is not saving when I try to change it from my admin panel. I think this may be due to already existing model instances. Here is the part of my current code: // models.py class Category(SortableMixin): name = models.CharField( _('name'), max_length=150, ) order = models.PositiveIntegerField( default=0, db_index=True, ) class Meta: verbose_name = _('category') verbose_name_plural = _('categories') ordering = ['order'] // admin.py class CategoryAdmin(SortableModelAdmin): class Meta: model = Category fields = ( 'name', ) sortable = 'order' The default value is set as 0 because of already existing objects. I tried to change their order manually in shell console but it did not help. I want to avoid deleting my objects and creating them again. Do you have any ideas how to fix this? -
Django timezone.now().time displays incorrect time zone
The subject is the simplest way that I can break down the problem that I am getting. I'm using Django 2.1 settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/New_York' USE_I18N = True USE_L10N = True USE_TZ = True views.py message = timezone.now().time message2 = timezone.now The above code is the fastest way to show the problem that I have. My model saves a datetimefield using the auto_now_add feature. models.py class Comment(models.Model): date_time = models.DateTimeField(auto_now_add=True, blank=True) When I display the field in HTML as {{ comment.date_time }} the correct date and time appears. However when I use my own formatting and break up the code as {{ comment.date_time.date }}: {{ comment.date_time.time }} then I cannot get the time to display in the correct timezone. I've tried the following alterations all to no avail. {% load tz %} {% localtime on %} {{ comment.date_time.time }} {% endlocaltime %} {{ comment.date_time.time|localtime }} {{ comment.date_time.time|timezone:"America/New_York" }} Does anyone know of a way to address this? -
No module named pip._internal
When I tried to install packages with pip, my terminal shows: File "/usr/local/bin/pip", line 7, in <module> from pip._internal import main No module named pip._internal My Mac comes with Python 2.7, I installed Python3.6 from MacPorts. I tried to fix it by uninstalling Python3.6 and Pip and reinstalling Python3.7 and Pip. When I use port select --set pip pip37 Then it shows: Selecting 'pip37' for 'pip' failed: could not create new link "/opt/local/bin/pip" pointing to "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/bin/pip": permission denied -
change apache current directory of python scripts
I've setup Apache to work with my Django App using mod_wsgi module. Here is the content of /etc/apache2/sites-enabled/yaraweb.conf : <VirtualHost my_server_ip:port> DocumentRoot /var/www/YaraWeb Alias /static /var/www/YaraWeb/yara/static <Directory /var/www/YaraWeb/yara/static> Require all granted </Directory> <Directory /var/www/YaraWeb/YaraWeb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess YaraWeb python-home=/var/www/YaraWeb/venv python-path=/var/www/YaraWeb WSGIProcessGroup YaraWeb WSGIScriptAlias / /var/www/YaraWeb/YaraWeb/wsgi.py And the structure of /var/www/YaraWeb is like this: /var/www/YaraWeb β manage.py β ββββvenv β β bin β β include β β lib β β pip-selfcheck.json | | share β ββββyara => django app | β admin.py | β apps.py β | forms.py β | __init__.py | β main.py | β migrations β | models.py β | static | β templates β | urls.py β | views.py β ββββYaraWeb β __init__.py β settings.py | urls.py | wsgi.py Everything works fine and the server is up but the problem is that when log current working directory in my codes, inside views.py, it returns /var/www, but i expect it to be /var/www/YaraWeb/. In other words, i need this snippet of python code to print /var/www/YaraWeb/: import os print(os.getcwd()) # actually prints /var/www/ Is there any Apache setting that can change this behavior? -
Iterate through all related objects changing a value
I'm trying to work out a way i can iterate through each related object and change the 'show' value from True to False. class Device(models.Models): name = models.Charfield(max_length=100) type = models.Charfield(max_length=100) class Log(models.Modles): device = models.ForeignKey(Device, related_name='msgs', on_delete=models.CASCADE) log = models.Charfield(max_length=100) date_time = models.DateTimeField(auto_now=True) show = models.BooleanField(default=True) I've tried the following but it's not working. device = Device.objects for host in device.all(): Log.objects.filter(device=host).update(show=False) but i get 'Log' object has no attribute 'update'. any ideas? Edit: Just to make it more clear what i'm trying to do. There are multiple 'Log' objects per 'Device' object. On a particular view i'd like to set the 'show' value to false because that means they have all been read and don't need to show in the top bar of my site any more. -
Django Channels stops working with self.receive_lock.locked error
I'm struggling with a problem using Django Channels to make a notification system. It works fine in local. In production (on Webfaction), it will work for fine for a few minutes, and then stop working with the following error message: ERROR - server - Exception inside application: File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/sessions.py", line 175, in __call__ return await self.inner(receive, self.send) File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__ await await_many_dispatch([receive, self.channel_receive], self.dispatch) File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/utils.py", line 57, in await_many_dispatch await task File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels_redis/core.py", line 400, in receive assert not self.receive_lock.locked() I'm using: aioredis==1.1.0 asgiref=2.3.2 channels==2.1.3 channels-redis==2.3.0 django==2.1.2 Redis 4.0.11 Python 3.6.6 This is all using django's development server. My consumer looks like this: class NotificationConsumer (AsyncJsonWebsocketConsumer): slight_ordering = True async def connect (self): self.user = self.scope["user"] await self.accept() group_name = "notifications_{}".format(self.user.employee.pk) await self.channel_layer.group_add(group_name, self.channel_name) async def disconnect (self, code): self.user = self.scope["user"] group_name = "notifications_{}".format(self.user.employee.pk) await self.channel_layer.group_discard (group_name, self.channel_name) async def user_notification (self, event): await self.send_json(event) The notification is sent when created, using a post_save signal: @receiver(post_save, sender=Notification) def new_notification (sender, instance, **kwargs): channel_layer = get_channel_layer() group_name = "notifications_{}".format(instance.employee.pk) async_to_sync(channel_layer.group_send)( group_name, { "type": "user.notification", "event": "New notification", "notification_pk": instance.pk, } ) My routing looks like this: application β¦ -
Using a custom fetch in Django
I'm using Django formsModel to create a form where the user needs to upload, with another inputs, his profile picture. The point is when the user uploads his picture, a modal with a cropper (I'm using cropper.js) shows up, and then the form data uploaded to the server needs to be the user inputs + cropped image data. So I made a "custom" fetch to POST the data, but it doesn't work. Can anyone help me? Parts of it looks like this: Here I "set" the cropped image to the formData; let formData = new FormData(document.querySelector('form')); document.querySelector('.crop').onclick = selectCrop = () => { cropper.getCroppedCanvas().toBlob(blob => { for(let f of formData){ if(f[0] === 'picture'){ f[1] = blob; } } }); modal.style.display = 'none'; cropper.clear(); } Here is my fetch: document.querySelector('button[type=submit]').onclick = saveFormData = () => { csrftoken = Cookies.get('csrftoken'); console.log(formData); fetch('/cadastro/novo/', { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, }, credentials: 'include', body: formData }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } -
geodjango model, cannot add new records in qgis - no active vector layer
Hello guys I have created some django models and I would like to be able to create new records. I was trying to add new points through qgis but I get - no active vector layer. I tried to grant all rights on postgres but still I couldn't add any new record. This is how I defined my model: class ww_manholes(models.Model): id = models.BigIntegerField(primary_key=True) gis_id = models.BigIntegerField() l_ass_obj = models.BigIntegerField() l_field_re = models.BigIntegerField() street = models.BigIntegerField() zip_code = models.BigIntegerField() regio_code = models.BigIntegerField() owner = models.BigIntegerField() ww_type = models.BigIntegerField() accuracy = models.BigIntegerField() x = models.FloatField() y = models.FloatField() x_ge = models.FloatField() y_ge = models.FloatField() z = models.FloatField() invert_el = models.FloatField() inv_start = models.FloatField() inv_end = models.FloatField() depth = models.FloatField() depth_star = models.FloatField() depth_end = models.FloatField() material = models.BigIntegerField() lining = models.BigIntegerField() coating = models.BigIntegerField() contractor = models.BigIntegerField() const_year = models.BigIntegerField() diam_nom = models.BigIntegerField() diam_inner = models.BigIntegerField() joint_type = models.BigIntegerField() cover_dim = models.BigIntegerField() cover_mat = models.BigIntegerField() access = models.BigIntegerField() rough_coef = models.FloatField() slope = models.FloatField() type = models.BigIntegerField() sc_condit = models.BigIntegerField() sc_perform = models.BigIntegerField() sc_fail_pr = models.BigIntegerField() sc_fin_imp = models.BigIntegerField() sc_soc_imp = models.BigIntegerField() sc_leg_imp = models.BigIntegerField() sc_env_imp = models.BigIntegerField() sc_red_sl = models.BigIntegerField() sc_imp_ph = models.BigIntegerField() sc_imp_rep = models.BigIntegerField() sc_rep_cos = models.BigIntegerField() sc_co_fail β¦ -
Django wsgi error after upgrade from 1.11 to 2.0 (load_middleware: argument to reversed() must be a sequence)
After upgrading from django 1.11 to 2.0 I got this error on my productive machine. mod_wsgi (pid=26504): Target WSGI script '/var/www/htdocs/myappdir/app_myapp.wsgi' cannot be loaded as Python module. mod_wsgi (pid=26504): Exception occurred processing WSGI script '/var/www/htdocs/myappdir/app_myapp.wsgi'. Traceback (most recent call last): File "/var/www/htdocs/myappdir/app_myapp.wsgi", line 13, in <module> application = django.core.wsgi.get_wsgi_application() File "/var/www/priv/venv/myappdirpy3/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/var/www/priv/venv/myappdirpy3/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 140, in __init__ self.load_middleware() File "/var/www/priv/venv/myappdirpy3/lib/python3.5/site-packages/django/core/handlers/base.py", line 36, in load_middleware for middleware_path in reversed(settings.MIDDLEWARE): TypeError: argument to reversed() must be a sequence It seems to be a probleme with the settings.MIDDLEWARE option, but it looks correct. Here is the MIDDLEWARE part from my settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] If I run "python3 manage.py runserver" directly on my productive machine, everything seems to work. But if I access the proejct through wsgi it is not working. Any idea where to start? -
How to write proper url for ajax if in django urls it is r'^post/(?P<post_id>.+)/$'
django urls: url(r'^post/(?P.+)/$', views.get_one_post, name='onepost') ajax: $(document).ready(function () { $(".answer").click(function () { var parent_id = $(this).attr('name'); $.ajax({ url: "post/", type: "POST", data: {parent_id: parent_id} }) }) }) -
Creating forms for custom User model
Im trying to create a form that could allow me to add profile picture to custom User object. I know that there is OneToOne method, although I want it to be stored directly in User. -
Python Complicated Query
I have this models as following: class Restaurant(models.Model): name = models.CharField(max_length=100) class UserPreference(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) fruit = models.MantToManyField(Fruit) vegetable = models.MantToManyField(Vegetable) class RestaurantPreference(models.Model): restaurant = models.OneToOneField(Restaurant, on_delete=CASCADE) fruit = models.MantToManyField(Fruit) vegetable = models.MantToManyField(Vegetable) how can i query in restaurant model using Preferences tables for example I need to get resturants that has same preference for spec user? please any one has an idea help me Many Thanks -
django built-in password_reset change connection from send_email
In my application i'm using the built-in auth views. I'm also using a postmark connection using django-anymail for some user email notifications. Example: email_backend = get_connection('anymail.backends.postmark.EmailBackend') mail = EmailMessage( subject=subject, body=message, to=[settings.DEFAULT_FROM_EMAIL], connection=email_backend ) I want to change the connection i'm sending email with in PasswordResetView. Is there any way i can give a keyword argument in the PasswordResetView.as_view() the same way i'm giving html_email_template_name='...' or success_url='...'? or do i have to rewrite PasswordResetView? -
Add new object to model with a foreign key
So this seems to be asked before but for the life of me, i cannot get any of the solutions to work. I have two classes, Device and Log. There are many logs per device and i'd like to be able to add new items to the Log objects. class Device(models.Models): name = models.Charfield(max_length=100) type = models.Charfield(max_length=100) class Log(models.Modles): device = models.ForeignKey(Device, related_name='msgs', on_delete=models.CASCADE) log = models.Charfield(max_length=100) date_time = models.DateTimeField(auto_now=True) I've been trying things like this in my view: device = Device.objects.filter(name=hostname) device.msgs.add(log=new_log_msg) but nothing i try is working. any ideas? -
how to get the value of checkboxs that checked using Django framework.?
How to get the value of checkboxs that checked and send it to views this is my form ! <form class="form-horizontal form-label-left"method="POST" action="{% url 'paperCustomization_submission'%}"> <div class="col-md-7 col-sm-9 col-xs-12"> {%for question_type in questions_type%} <div class="checkbox" id="checkbox-question" > <label> <input type="checkbox" id="question_type_id" value="{{question_type.question_type}}" onclick="function1();"class="flat"> {{question_type.question_type}} </label> </div> {%endfor%} </div> -
Do Django CMS have any pre_publish signals?
Use-case: I have created a workflow, where there are Content requester, Content validators with different permissions. Now I have given the publish permission to content-publisher. Content publisher needs to check whether all the validators have validated the content changes before publishing. Lets say even if the validator is not validating we need a way to disable publishing so that publisher will not be able to publish the changes. post_publish signal is not useful here as the page is already published. Is there any standard way of doing this ? -
Redirect subfolder request to Passenger
I want to redirect all requests like mysite.com/subfolder/... to Django application over Passenger and all other requests to the website running under some php cms. File structure: .htaccess subfolder/ .htaccess some cms files Content of root .htaccess: RewriteEngine on ... RewriteConds and RewriteRules generated by php cms Content of subfolder/.htaccess: PassengerAppRoot "/home/username/djangoapplication" PassengerPython "/home/username/virtualenv/webapp/2.7/bin/python2.7" The problem is about root .htaccess. When root .htaccess is empty (constails only RewriteEngine on) requests like mysite.com/subfolder/... are handled by subfolder/.htaccess and Django application loads. But when root .htaccess contains lines generated by php cms all requests like mysite.com/subfolder/... leads to the 404 error page from cms. So I want to filter requests like mysite.com/subfolder/... to subfolder/.htaccess before RewriteRules from cms will replace it with 404 error page, but I can't figure it out how to do it. -
Displaying 'fake' queryset group names in django model form - SelectMultiple
Hello I am junior django dev I will appreciate any help! I have django groups like this: "Super group", "Mega group", "test_1", "test_2", "test_7", "Nice group", "test_16" (....) Groups test_X are related via X (id) to another model that contains it's title. That means I can do something like this: x = Groups.objects.get(pk=6) # getting group of name "test_6" x.rel_group.title # shows "Super title" instead of "test_6" I have a manager that change names of test_X groups to related object titles and returns specially prepared queryset... just to display it right, without database change: class AllGroupsManager(models.Manager): def get_queryset(self): queryset = super(AllGroupsManager, self).get_queryset().exclude(rel_group__start_date__lte=datetime.now()-timedelta(days=3)) for number, t in enumerate(queryset): if 'test_' in t.name: t.name = t.rel_group.title return queryset This is my model form: class TestForm(forms.ModelForm): class Meta: model = Test fields = ( 'title', 'price', 'body', 'group', ) widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={'class': 'form-control', 'min': 0.0}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'group': forms.SelectMultiple(attrs={'class': 'form-control chosen', 'data-placeholder': 'Wybierz grupΔ'}), } def __init__(self, *args, **kwargs): super(TournamentForm, self).__init__(*args, **kwargs) self.fields['group'].queryset = Group.get_all.all() # using my manager here print(self.fields['group'].queryset) # I can see that all group names are changed from test_X to specyfic names like "Great name" Inside It I am using my manager on β¦ -
Django-social-auth {% url 'social:begin' 'google-oauth2' %} is not adding a user to db
<a class="btn btn-success btn-outline btn-sm" href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">Verbinden</a> Why does this Link not add an user to the social_auth_usersocialauth table. Everything else in the login procedure works fine. What are the possibilities? If you need more code just write an comment -
Django Rest API VIEWSET custom validation on post request
I'm new to django rest framework. My api views.py: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer and serializer.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'price', 'status') want to override price field. -
How to Use Django Backend for Electron Js with Mysql Database(any)?
I have created an Electron Desktop Application. I need to make backend to insert data into the database and retrieve from database, actually some CRUD operations but I know Django well. How can I configure Django with Electron js ? -
Djongo redefine the structure of ArrayModelField
I am defining ArrayModelField using Djongo. It looks great, but the problem with ArrayModelField is I can only add it as Array of Objects, not just Flat List. Is there any way by which I can add it as Flat List? Example: # models.py from djongo import models class Option(models.Model): option = models.CharField(max_length=100) class Meta: abstract = True def __str__(self): return self.option class Quiz(models.Model): _id = models.ObjectIdField() question = models.TextField(null=True, blank=True) options = models.ArrayModelField(model_container=Option) answers = models.ArrayModelField(model_container=Option) Using this I can create a document as follows, But I want to save it in this format, Is there any way by which I can do this now? Thanks in advance.