Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Windows Service Starts but nothing seems to be happening
I created a python script that will start Django in the background: # filename: Service.py from subprocess import Popen from sys import stdout, stdin, stderr import time import os serverpath = os.path.abspath('server/manage.py') print("running django server") process = Popen('python '+serverpath+' runserver', shell=True, stdin=stdin, stdout=stdout ,stderr=stderr) print(process.communicate()[0]) and then with pyinstaller I create a service.exe and then move all the folders to the correct dist\service directory. When I execute service.exe Django server runs perfectly. From here I use nssm.exe. I run the following command: nssm.exe install myService a GUI popups and I point the path to service.exe. It successfully creates the service. I open services.msc goto myService and start it. It starts with no error messages and is now running. I goto my browser and type in http://127.0.0.8/admin but no page shows up. I'm guessing something isn't working, what exactly though I don't really know. Any help understanding what I am doing wrong here would be awesome! Hard to debug this with no error messages from the services and a terminal does not popup this time to notify me that it is working like before when I would just run the service.exe manually. -
Can I have multiple query_sets for a view?
I have a view that I allow get, put and delete. I want to have a queryset for my get and a different one for my put and delete (2 different querysets). I guess in my get_queryset method, I can check the request action but I just wanted to double check and see if this is the correct way of doing it. -
Google Oauth2 with Django
Can someone help me to define how is google oauth2 works and what infrastructure should I develop that google can auth with my Oauth2 server? I want google be the oauth2 client not the server. For example : Is client ID unique for each users? What is state in the params .... And can you give me a link of open source project that is running oauth2 server that google can auth with it. https://developers.google.com/actions/identity/oauth2?oauth=code -
Django 3 field in model, choose one in serializer
I Got model, let's say People and 3 text fields : man woman and child. I want in serializer do that there is if statement which choose which of this fields is serialized. -
How to run query against multiple non-db field values
I am having hard times to find some smart and reliable way how to run multiple annotations per every specified datetime I provide at the start of query. My data from datetime import datetime business_dates = [ datetime(year=2016, month=1, day=5), datetime(year=2016, month=1, day=6), datetime(year=2016, month=1, day=7), ] Desired output [ {'date': datetime(year=2016, month=1, day=5), 'employee_count': 22}, {'date': datetime(year=2016, month=1, day=6), 'employee_count': 24}, {'date': datetime(year=2016, month=1, day=7), 'employee_count': 29}, ] What I dont want: Loop business_dates and run one separate query for each date. In case of 100 dates, I dont want to run 100 separate queries. Lets say, running subqueryies is alright for now. Any ideas? -
How to set foreign-key to <null> in Django (without on_delete=models.SET_NULL)
Could you please advice how to set foreign-key to "NULL"? I the following example I want to override delete method in order to not delete images but instead set their FK to "NULL" in order to recover and reconnect them with the parent objects later on. def delete(self, using=None, keep_parents=False): self.foreighnkey = None # foreighnkey is the fk field's name self.save() # https://stackoverflow.com/questions/4446652/django-how-to-set-a-field-to-null # doesn't work this way Thank you P.S. Parent objects will stay intact, so that use their delete methods is not an option -
Saving result of function in session results in TypeError object not JSON serializable
I have a function in a services.py file: def someFunction(): if choice == 'Choice1' result1 = Choice1.objects.all.order_by('?')[0] result2 = Choice1.objects.all.order_by('?')[0] result3 = Choice1.objects.all.order_by('?')[0] elif choice == 'Choice2' result1 = Choice2.objects.all.order_by('?')[0] result2 = Choice2.objects.all.order_by('?')[0] result3 = Choice2.objects.all.order_by('?')[0] result = [result1, result2, result3] return result I pass it to the view like so: def template(request): request.session['result'] = someFunction() #save result to session result = request.session['result'] #retrieve saved result from session context = { 'resulting': list(result) } return render(request, 'project/template.html', context) And then passed to the template etc. However this results in 'TypeError at /template object type of resulting is not JSON Serializable.' If I don't try to save the function results to the session everything works fine. I'm not sure what I'm doing wrong, or if there's a better way to achieve saving the result of a function to the session. Any help is appreciated. -
Setting up Sentry for Django on DigitalOcean
I followed the docs, but nothing seems to appear in Sentry In my pipenv I did $ pipenv install 'sentry-sdk==0.7.14' and I have sentry-sdk = "==0.7.14" in my pipfle I added the following to the project settings file import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://30bb32a65a60494f953a7bb445b964c1@sentry.io/1456879", integrations=[DjangoIntegration()]) Restart my Gunicron and nginx sudo systemctl restart gunicorn sudo systemctl restart nginx Nothing appears in Sentry, what am I missing here ? -
Django making a cycle in templates
i have two models, with relationship 1-N. And i want to edit my change_from_objects_tools.html to do a cycle that while i have aditamento.objecs is creating buttons. Project Model class Projeto(models.Model): field1 = ........ field2 = ........ Aditamento Model class Aditamento(models.Model): processo = models.ForeignKey(Projet, on_delete=models.CASCADE,verbose_name="Projecto",related_name='ProcessoObjects') field1 = ..... field2 = .... Projeto Admin class AditamentoInline(admin.StackedInline): form = AditamentoForm model = Aditamento extra = 0 max_num = 4 class ProjetoAdmin(admin.ModelAdmin): inlines = [AditamentoInline] change_from_objects_tools.html {% load i18n admin_urls %} {% block object-tools-items %} <li> {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> </li> <!-- Something like this --> {% for aditamento in Aditamento.all %} <a href="" target="_blank">{% trans "New Button" %}</a> {% endfor %} <!-- --------------- --> {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} {% endblock %} -
How to access to queryset in change_list block content for Django ModelAdmin
I need to access to queryset (including filtering, searching, etc)that is used to generate list in change_list.html This is in django 2.2.1 and Python 3.6 admin.py class CompanyAdmin(admin.ModelAdmin): list_display = ('name', 'city') list_display_links = ('name', 'city') list_filter = ('city', ) search_fields = ('name', ) change_list_template = 'admin/contacts/company/change_list.html' admin.site.register(Company, CompanyAdmin) change_list.html {% extends "admin/change_list.html" %} {% block content %} {{ block.super }} {% endblock %} -
Is there a way I could upload a photo from the Django Admin pointing to a div?
I'm almost done fixing my Django portfolio when I bumped into a problem when choosing a photo for one of the pages of my site: The problem here is the dropdown doesn't show anything! My models.py is from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='/img') I have an /img folder on the main project folder and the static folder. You can see what I'm talking about here https://s3.amazonaws.com/django-error/problem1.mov Did I miss anything? -
Filtering languages queryset looping on tuple (code, name_translated)
I need to filter a queryset based on language field (language code) from an input. For example in italian, a user might search for 'italian'. So the first thing I've done is created a list of tuple containing (lang_code, name_translated) as following: # List of tuples (code, translated_name) TRANSLATED_LANGUAGES = [(l[0], get_language_info(l[0])['name_translated']) for l in LANGUAGES] Here is my method for filtering: def filter_by_languages(self, queryset, name, value): for l in TRANSLATED_LANGUAGES: if value in l[1].lower(): queryset.filter(Q(lang_src__code__iexact=l[0])) return queryset.distinct() It returns a queryset which is not filtered. I must misunderstanding something. -
Django make ChoiceField not requied
i am building form where i have dynamical removing of inputs in rows. Everything works fine except when the row contains ChoiceField. ChoiceField is requied by default and when i remove it and submit, the form cannot be validated. Is there a way to set the ChoiceField as not requied, like for example here with ModelChoiceField: ModelChoiceField(queryset=Model.objects.all(), requied=False, empty_label=None) I tried to set the choices like that, but i still couldnt use requied=False: #In models: choices = ( ('', '-') #Tried also as None, '-' (0, 'Yes'), (1, 'No'), ) #In forms: forms.ChoiceField(choices=Model.choices, label=""), -
Django Project - posts from a json file are not rendering in the browser
As part of a Django project, I am trying to retrieve the contents of a json file (which is the project directory where the manage.py file is) and display them in the browser along with other posts. I have followed these instructions in the shell, with no errors, so it should have saved. (InteractiveConsole) >>> import json >>> from socialmedia.models import Post >>> with open('posts.json') as f: ... posts_json = json.load(f) ... >>> for post in posts_json: ... post = Post(title=post['title'], content=post['content'], author_id=post['user_id']) ... post.save() However, on running the server, the posts are not displayed on the page. This is the code in the home.html page {% extends "socialmedia/base.html" %} {% block content %} <h1>Fakebook</h1> {% for post in posts%} <article class="media content-section"> <img class="rounded-circle article-img" src="{{post.author.profile.image.url}}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y"}}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} and this is the relevant code in the views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post #import the Models Post from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) … -
HTML content minification in Django CMS
I would like to implement HTML content minification in Django CMS. The idea is to intercept the action of saving the content of a TextPlugin (using djangocms-text-ckeditor), and process the HTML before it is saved to the database. Is there a way to do this, for example, using signals? Or is there any other known solution (i failed to find any) ? -
Connecting ReactJs Admin Dashboard to Django Admin
I want to create a custom Admin Dashboard (with fully customised animations, colours, themes). How to replace the default admin in Django and create a admin dashboard which can fetch data from Django tables with all the securities and middlewares in place. -
Conditional in model
quick question. I struggle with writing a conditional in model. If I use code below I get desired .png file, but I'd like to specify that if tripName == 'russia' than do the condition. However when I add that line code goes immediately to the else. Any ideas? class Trip(models.Model): tripName = models.CharField(max_length=64) if tripName: tripLogo = models.ImageField(default="russia.png", upload_to='trip_pics') else: tripLogo = models.ImageField(default="default_trip.png", upload_to='trip_pics') -
I can't run Django in non-local mode
I have a VPS with Ubuntu 18.04 server OS. I installed Apache 2 on it, and I have a domain. I configured Let's Encrypt so that my website has HTTPS and all HTTP traffic is redirected to the HTTPS. My default page is /var/www/mydomain.net/html/index.html and when I type my domain in a browser it shows the content of that page, so that's great. But now I want to create a website with Django, so I executed (in a virtual env) django-admin startproject mydomain inside the directory /var/www/mydomain.net. Then I executed python3 manage.py runserver 0.0.0.0:8000 as it is mentionned in this tutorial but instead of showing the default django "Congratulations, it works!" page, my browser is loading for an infinite time without showing any page. I tried to set Debug to False and add "*" in ALLOWED_HOSTS but nothing fixed the issue. -
uwsgi service cannot be restarted
django app delpoyed on uwsgi & nginx, works if I manually start uwsgi app with following command. # sudo uwsgi --http 0.0.0.0:8000 --home /home/$USER/djangy/venv --chdir /home/$USER/djangy/testproject --wsgi-file /home/$USER/djangy/testproject/testproject/wsgi.py But when I enable uwsgi service # sudo systemctl restart uwsgi.service it exits with exit code=1 and fails to restart here are the permissions of .service file -rw-r--r-- 1 root root 296 May 10 11:41 /etc/systemd/system/uwsgi.service what am I missing? -
About objects in models
I create the some models in my models.py file this is my code: class Topic(models.Model): top_name = models.CharField(max_length=50 , unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.CharField(max_length=20 , unique=True) name = models.CharField(max_length=50,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.CharField(max_length=50 , unique=True) date = models.DateField() def __str__(self): return str(self.date) and in views.py file when write this code in my function : webpage_list = AccessRecord.objects.order_by('date') I have this error : class "AccessRecord" has no objects I dont know what can i do for this error my Djnago version 2.2 -
How to print object properly in django python?
I am new here in django, I want to print my data, i am using this function to get data from table, page_data = Pages.objects.all().filter(id=id), i am getting this response <QuerySet [<Pages: Page 567>]>, why it shows only title column data ? It should have to show all this data, can anyone plese help me how to show all this data with print in cmd ? -
Integration of checkall javascript in Django
I have a list (as a table) of some data, I have a button on each row which via the view assigns the record (a sample) to another record (a container) via a m2m <a href="{% url 'depot:change_container' operation='add' pk=container.container_id fk=unassigned.sample_id %}" class="badge badge-primary" role="button">. This works. I've been asked to add a 'checkall' option, I have achieved this through javascript. I've nested the code into a form. So how do I pass multiple records (rather than just 1) into Django from the javascript checkboxes so that any samples that are checked get assigned to their container? # javascript <script type="text/javascript"> function toggle(source) { var checkboxes = document.querySelectorAll('input[type="checkbox"]'); for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i] != source) checkboxes[i].checked = source.checked; } } </script> The template: <div class="float-left col-md-4"> <h4 class="kap">Unassigned Samples</h4> <div class="table-responsive"> <form class="" action="" method="post"> <table class="table-striped table-dark"> <thead> <tr> <th style="padding-left:5px;"> <input type="checkbox" onclick="toggle(this);" /> </th> <th>E.N.C.S</th> <th>Current Location</th> </tr> </thead> <tbody> {% for unassigned in unassigned_samples %} <tr> {% if unassigned not in container_contents %} <td style="padding-left:5px;"><input type="checkbox" /></td> <td style="margin:10px; padding:10px;"><a href="{% url 'depot:change_container' operation='add' pk=container.container_id fk=unassigned.sample_id %}" class="badge badge-primary" role="button"> <i class="fas fa-arrow-left fa-2x"></i> </a></td> <td>{{ unassigned.area_easting }}.{{ unassigned.area_northing … -
django.core.exceptions.ImproperlyConfigured: DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
i got an error like this. I am very new to python programming.Please help me to resolve this.And let me know how to set PYTHON ENVIRONMENT VARIABLE -
Wrong redirects when using defaultRouter() for ModelViewSet in Django-REST-framework
I have a Django Project where i made 3 Different Apps: "blog", "users", "api". It is a Website where messages can be posted by using a model Post. I want to use an Django Rest API for accessing the Model. It works, but it messes with some redirects of the UpdateView and DeleteView of "blog". I think it could be a problem with using DefaultRouter() ? When i try to use my blog/PostupdateView blog/PostDeleteView ( inherited from UpdateView and DeleteView) views, i keep getting redirected to /api/blog/postid/ instead of just accessing my detailView where the path should be just /blog/postid/ and i cannot figure out why. my Post Model: class Post(models.Model): ... def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) my Serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title', 'content', 'date_posted', 'author', 'rooms') my api view for Post: class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer My urls Files: main urls.py: urlpatterns = [ ... path('', include('blog.urls')), path('api/',include('api.urls')), ] blog/urls.py: urlpatterns = [ ... path('post/<int:pk>/', PostDetailView.as_view(),name='post-detail'), path('post/new/', PostCreateView.as_view(),name='post-create'), ... ] api/urls.py: router = routers.DefaultRouter() router.register('post', views.PostView) urlpatterns = [ path('',include(router.urls)) ] my PostCreateView in blog/views.py class PostCreateView( LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Post fields … -
Can i develop an website which calls a script each time when i click on a button and takes human input from web page using Django?
I have few python scripts which run on the Centos server and when you run those it takes human input and updates few files . Now i want to call those scripts from web page and give input from web page .So that script will execute and update files on the backend . I thought to do this using Django and started running app . Now i want to know what are steps to follow to reach my goal.