Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django served with Gunicorn as Systemd service starting, but app not running
[Unit] Description=IT Database Application Daemon After=network.target StartLimitIntervalSec=0 [Service] Type = simple Restart = always RestartSec = 1 User = <username> WorkingDirectory = /home/<username>/applications/it-database ExecStart = /usr/bin/env gunicorn --bind 0.0.0.0:9001 dsg-it-database.wsgi [Install] WantedBy = multi-user.target Unfortunately I'm not being given a whole lot to go off of, so I'm hoping someone more versed can spot what I've done wrong. I have gone through and looked into each line to understand what's happening here, and with my limited knowledge this is all good. [<username>@<server> it-database]$ /usr/bin/env gunicorn --bind 0.0.0.0:9001 dsg-it-database.wsgi [2019-02-25 17:20:12 -0500] [87770] [INFO] Starting gunicorn 19.9.0 [2019-02-25 17:20:12 -0500] [87770] [INFO] Listening at: http://0.0.0.0:9001 (87770) [2019-02-25 17:20:12 -0500] [87770] [INFO] Using worker: sync [2019-02-25 17:20:12 -0500] [87774] [INFO] Booting worker with pid: 87774 The service starts, but my application does not run & nothing is bound to 9001. When I run my execstart from another screen, it starts and everything is working correctly, so behind systemd I'm a bit blind & hoping you guys can offer some guidance. -
Django TruncHour without other date fields
I have a series of timestamps from crawled Posts. Now I want to show a statistic where the activity of an author of the posts will be shown. For this I want to filter the times of the posts (Models Posts contains the datetime field 'timestamps') in days and hours. The filtering for the days works. I want to show at which times (11:00, 09:00 etc.) the posts were created. I wanted to filter the dataset like from django.db.models.functions import TruncHour from django.db.models import Count from .models import Posts posts = Posts.objects.all() hours = posts.annotate(hour=TruncHour('timestamp')).values('hour').annotate(count=Count('id')) but with this filter I receive a bunch of hours which contains different days, month, years... I only want to receive the pure hour without other parameters. Is there a way to go? Any clue is welcome... -
How to disable escape for Django model field's value in template when rendering fields manually
I am working on one of my colleague's Django (Django 2.1.4) projects. I spent a couple of days to try to figure out how to disable auto escape for Form field's value when rendering it manually in a template. {% autoescape off %} and {{form1.LastName | safe }} all don't work. Here are some relative codes. Form.py class tblstudentinfomodelform_page1(forms.ModelForm): LastName = forms.CharField(max_length=30, required=True) views.py def application(request,application_num) form1 = tblstudentinfo.objects.get(ApplicationNumber=application_num) ... form1_forms = tblstudentinfomodelform_page1(initial=form1.__dict__) if form1 else tblstudentinfomodelform_page1(initial=form1) ... return render(request,'appinfo.html',{'form1':form1_forms}) appinfo.html <th>{{form1.LastName}}<br>{{form1.LastName.errors}} {{form1.LastName.value}} </th> Some tests here: LastName's value is &#350;haha test1: add {% autoescape off %} at the top of the template and {% endautoescape %} at the bottom result1: {{form1.LastName.value}} displays correctly -- Şhaha, but input textbox shows &#350;haha run result -- html page test2: delete autoescape tag and add safe filter <th>{{form1.LastName | safe}}<br>{{form1.LastName.errors}} {{form1.LastName.value |safe}} </th> result2: get the same result, looks like that safe filter only worked on form.field.value Any suggestion? Thank you. -
Django - Model choices from another model's choices that are already selected
So I have one model that has a ManytoMany field which selects choices from another primary model. I want another model that has a ManytoMany field who's choices are only the selected choices of the first model. Here is the current code for the models, and I'd want to select from the AdminChoices selected choices class choices(models.Model): choices = models.CharField(max_length=300) def __str__(self): return self.choices class AdminChoices(models.Model): choice1 = models.ManytoManyFields(choices, related_name="adminchoices_choice1_related") choice2 = models.ManytoManyFields(choices, related_name="adminchoices_choice2_related") class UserChoices(models.Model): choice1 = "choice that can only be chosen from selected AdminChoices choice1" choice2 = "AdminChoices choice2" I'm making an application where users can create a hardware configuration. A field in this model represents a slot and only one choice can be selected for the slot. These choices would have to be approved by an admin first to ensure that the slot can accept that choice. This is where the AdminChoices model comes in, where an admin would have access to a global admin configuration that approves choices for a slot, which would then allow a user to select this choice in their personal configuration. I'm not sure if I'm taking the right approach, how would I go about making this model? -
How can I count the messages coming from a view inside a template?
I'm using Django's messages framework to pass messages from my view functions to my templates. I want a template to contain some HTML only if the number of messages is greater than 1. Is there a way to do this? I've tried the following: {% if messages.count > 1 %} <html for multiple messages> {% else %} <html for just one message> {% endif %} But messages.count doesn't seem to exist. -
import urlresolvers from django.core in django 2 after upgrading from django 1
trying to import: from django.core import urlresolvers I get: ImportError: cannot import name 'urlresolvers' from 'django.core' This is because UrlResolvers are deprecated and replaced with Django.Url. However I am looking for the actual UrlResolvers in order to find: urlresolvers.get_resolver(None) I cant find where this method has gone in the documentation. Using Latest django and Python 3.7 now. -
How to update Auth django with Firebase auth
We are migrating everything to micro services. The django app in production use allauth. What will do expert like you? I have to use the Strangler pattern here. Create a oAuth provides for allauth? Rest for login/logout/new-accounts? I like have some advises, ideas please. Thanks. -
How to change maximum height of Django-CKEditor and add scroll?
I can not set a maximum pro height, it keeps increasing its height infinitely, I just added a plugin to add code and its dependencies. My settings in the settings.py file CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = MEDIA_ROOT CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono-dark', 'toolbar_CustomConfig': [ # .... {'name': 'links', 'items': ['Link', 'Unlink', ] }, ], 'toolbar': 'CustomConfig', 'height': 350, 'width': '100%', 'tabSpaces': 4, 'extraPlugins': ','.join([ '# .... ]), } } I also tried edit the config.js file CKEDITOR.editorConfig = function (config) { config.codeSnippet_theme = 'monokai_sublime'; config.resize_maxHeight = 350; }; -
python django add variable to session from function and access it from another view function at same time
I'm trying to add session variable but it is not accessible from another function while the first function is still running, example is below def index(request): request.session['logs'] = [] #I define the new variable here in session return render(request,"index.html") def assigntoken(request): #I got list of users from post request to assign token to each of them I call a class called AssignToken v = AssignToken() #AssignToken class has attribute called log_lst I assign it to session request.session['log'] = v.log_lst #by making v global I can access it from another function while it still running, but request.session['logs'] is still empty until function finish, why? v.start(users) #this will start loop in users list to assign tokens return redirect('/result') def result(request): #while assigntoken function still running I should be able to access /result to see live logs but when I try to access request.session['logs'] I found it empty, it only has data after assigntoken finish running context = {'logs':request.session['logs']} return render(request,"results.html",context) -
Setting current site in django - nginx
The question is what is the best way to initially set or dynamically change the current_site in the django sites framework? This question is similar to question Dynamically Set Site ID, which was asked in 2014 I have two different domains, one of which contains 'verse'. The recommended approach, from what I have read, is to read some environment variable in settings.py and set the ID accordingly. However, socket.gethostname() will not work because nginx points both domains to the same host. Further, nginx will not easily set a readable variable, although there are two configuration files. Finally, you cannot read the url in settings.py, because you cannot access a request. etc. Instead, building on the question linked above, I added this middleware: class SiteMiddleware(MiddlewareMixin): def process_request(self, request): if 'verse' in request.build_absolute_uri(): settings.SITE_ID = 2 current_site = Site.objects.get(domain__icontains='verse') else: settings.SITE_ID = 1 current_site = Site.objects.get(id=1) request.current_site = current_site return None Which is working, but requires disabling the existing django.contrib.sites.middleware.CurrentSiteMiddleware It seems that CurrentSiteMiddleware needs a set site_id for a site query in first place. So, is this way safe, and more importantly is there an easier way to do this? -
How to deploy django channels 2.x on AWS Elastic Beanstalk?
This tutorial covers channels 1.x's deployment. However, this does not work with channels 2.x. The failing part is the daemon script, which is as follows: files:"/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_daemon.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash # Get django environment variables djangoenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/%/%%/g' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` djangoenv=${djangoenv%?} # Create daemon configuraiton script daemonconf="[program:daphne] ; Set full path to channels program if using virtualenv command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 <your_project>.asgi:channel_layer directory=/opt/python/current/app user=ec2-user numprocs=1 stdout_logfile=/var/log/stdout_daphne.log stderr_logfile=/var/log/stderr_daphne.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$djangoenv [program:worker] ; Set full path to program if using virtualenv command=/opt/python/run/venv/bin/python manage.py runworker directory=/opt/python/current/app user=ec2-user numprocs=1 stdout_logfile=/var/log/stdout_worker.log stderr_logfile=/var/log/stderr_worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase … -
Redirect after saving item via ModelForm
I'm using a modelform to add some items to one of my models. in view I have : def create_cf(request, fslug): detail = Fd.objects.get(slug=fslug) if request.method == 'POST': cf = CFForm(request.POST) if cf.is_valid(): instancecf = cf.save() return redirect('cf:create_cf') else: cf = CFForm() return render(request, 'cf/create_cf.html', {'cf': cf}) template: <form action="/create_cf/" method="post"> {% csrf_token %} {{cf}} <input type="submit" value="Submit"> </form> though, and unfortunately, I get a Page Not Found Errorat /create_cf.html... What am I doing wrong?? many thanks in advance -
run some function after taking input from api django
i have one webapp where user post image and then opencv calculate its detials like width,height and show back. i got this from webapp but when i trying the same with api i can't figure out how should i do this here me code: Serializers.py from rest_framework import serializers from results.models import Result import cv2 class ImageSerializer(serializers.ModelSerializer): class Meta: model = Result fields = ('title','pub_date','medium','compound','detail','outputval','image','uploader') models.py: class Result(models.Model): title = models.CharField(max_length=200) pub_date = models.DateField() medium = models.CharField(max_length=200) compound = models.CharField(max_length=200) detail = models.TextField() outputval = models.TextField(default='rsult not calculated', null=True, blank=True) image = models.ImageField(upload_to='images/') uploader = models.ForeignKey(User, on_delete=models.CASCADE) # will be changed to not delete in update views.py: from rest_framework import viewsets from .serializers import ImageSerializer from results.models import Result import cv2 class ImageViewSet(viewsets.ModelViewSet): queryset = Result.objects.all() serializer_class = ImageSerializer opencv function: def opencv(self,img_path): image = cv2.imread(img_path) height = image.shape[0] width = image.shape[1] channels = image.shape[2] values = (" the height is %s , width is %s and number of channels is %s" % (height, width, channels)) return values what i want to do take image as user input and show the output in outputval fields. -
How to differentialte between post and other requests in Django custom serialisers class
class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta : model =User validators = [] .... .... def validate(self, data): .... .... def create(self, validated_data): .... .... def update(self ,instance, validated_data): .... Here is serialiser defined for a userModel. When this I hit this api the validators always run before create for Post or update for Put is called. I want to make some checks on validators depending on Post or Put or any other method. Is there a way to do so -
Django manage.py test: “database backend does not accept 0 as a value for AutoField” (mysql)
I am trying to run the Django tests file using: python3.6 manage.py test I use: MySQL 5.5.62, Python 3.6, Django 2.0.0 It starts installing a test DB and fails with the error: ValueError: The database backend does not accept 0 as a value for AutoField. I searched for this error but all the topics I found were related to migrations, such as this one. I have no problem with migrations, they run smoothly. Traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 59, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/usr/local/lib/python3.6/site-packages/django/test/runner.py", line 548, in setup_databases self.parallel, **kwargs File "/usr/local/lib/python3.6/site-packages/django/test/utils.py", line 176, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 68, in create_test_db run_syncdb=True, File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 141, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state … -
django - 'ModelName' object is not iterable
I have a model class named TemplateImages that holds the reference to images in my media folder. I want to display the images in a loop on a html file. Here is my models.py code: class TemplateImages(models.Model): image = models.ImageField(upload_to='template_images') # template_images/en/chronological/en-chronological-resume-1.png. type = models.CharField(max_length=40) # e.g. chronological, functional, combination, coverletter language_code = models.CharField(max_length=7, choices=languages.LANGUAGE_CHOICES, default='en') # en. def __str__(self): return '{}'.format(self.image) Here is my views.py code: def templates(request): ... language_pref = request.user.userprofile.language_preference chronological_images = core_models.TemplateImages('chronological', 'en') ... return render(request, 'templates/templates.html', { ... 'chronological_images': chronological_images, ... }) Here is a screen shot of my db: On my html page, I have placed the following django for loop to display the 25 images on the page: {% for c_image in chronological_images %} {{c_image.image|file_url|safe}}" {% endfor %} I receive the following error message: 'TemplateImage' object is not iterable I have searched google, but cannot locate any useful examples. Can someone explain what I have done wrong? -
Transitioning from a Django-Rest/React project to a Django-Rest/React Native project
So I've been working on a project that has the backend written in Django/Django-Rest and the frontend currently written in React. It's been great but the overall goal of the project is supposed to be a mobile app, which we have turned to React Native for. I'm not seeing a lot of resources about transitioning between React and React Native. How similar are they? Is it even possible to port over any of our front end code from React to React Native? Can you even integrate a Django/Django-REST backend into a React Native frontend? I know these are some very open ended questions but I haven't found a ton of resources on this so any help would be greatly appreciated. Thanks -
Heroku SQLAlchemyJobStore config
I am trying to config some persistence scheduled jobs using SQLAlchemyJobStore in a Django 2.x app hosted in Heroku. job_stores = { 'default': SQLAlchemyJobStore(url=settings.SQLALCHEMY_DATABASE_URI) } SCHEDULER = BackgroundScheduler() However, doing this and deploying to the server it crashes. raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> -
Django sendmail with bcc via gmail
Im trying to send Emails with bcc my testscript if form_email.is_valid(): toaddr = form_email.cleaned_data['email'] tocc = form_email.cleaned_data['cc_email'] subject = form_email.cleaned_data['subject'] message = form_email.cleaned_data['message'] signature = form_email.cleaned_data['signature'] msgHtml = message + '<br><br>' + signature SMTPserver = 'smtp.gmail.com' toaddr = [toaddr] tocc = [tocc] user_bcc = [user_bcc] msg = MIMEMultipart('alternative') msg['From'] = email_user msg['To'] = ', '.join(toaddr) msg['Cc'] = ', '.join(tocc) #msg['Bcc'] = bcc msg['Bcc'] = ', '.join(user_bcc) msg['Subject'] = subject msg.attach(MIMEText(msgHtml, 'html')) try: conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(email_user, gmail_app_pass) conn.sendmail(email_user, toaddr, msg.as_bytes()) conn.quit() except: conn.quit() messages.warning(request, 'Something went wrong, Email not sent', extra_tags='alert') return redirect(reverse('detail', kwargs={"album_id": album_id})) messages.success(request, 'Email sent') return redirect(reverse('detail', kwargs={"album_id": album_id})) When I open in sent emails or from receiver inbox Bcc is shown but first is not Bcc and second on Bcc's Emails is no Email in Inbox. Sent email Some informations are direct from the Database -
How to add fields dynamically to all my Django forms through the Admin class?
I want to be able to get some fields that are related to a model and add them to this model form (for all models and forms in my project). -
Finding an username using an id in django
I would like to use an id to search my database for the username that belongs to that id. I have a url.py setup to give the id via an url variable then I pass it onto the views.py that passes it to the template At the moment I have the following: models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass def __str__(self): return self.email docfile = models.FileField(upload_to='static/users/',) views.py def ProfileView(request, id): return render(request, 'pages/profile.html', {"id":id}) urls.py path('profile/<int:id>', views.ProfileView, name='Profile') profile.html <div class="mainusers"> <div class = "userLine"> <p>{{ id.username }}</p> <!-- I know this wouldn't work, It's just a place holder at the moment --> <center><p></p><p class="mainfont"><u>{{ id.username }}</u><p></center> <div class="circular--portrait"> <img id="ProfileBox" src="../static/users/{{ id.username }}.gif" onerror="this.onerror=null;this.src='static/users/default.gif';"/> </div> <center><p><br></br> Date Joined: {{id.date_joined}}</p></center> {% if id.is_superuser %} <center><p>Developer</p></center> {% endif %} <div class="wrapper"> <button class="logout" onclick="window.location.href='{% url 'logout' %}'">Logout</button> <button class="logout" onclick="window.location.href='/invgen'">Generate Invite Code</button> </div> -
How to update data in django model to title case in views?
I'm trying to change a column of strings like 'HOSPITAL ZERO', "HOSPITAL ONE" from the database into title case or 'Hospital zero' in the views.py or models.py. I've tried both and can't get either to work for me. Here is my code in views.py. Column is in Hospital Model under name, i.e. Hospital.name. def results(request): if request.method == "GET": Q=() out_words = request.GET.get('s') context = RequestContext(request) #here is where I tried to change it qs = Price.objects.annotate(hospital__name=Lower('hospital__name')) table = PriceTable(qs.filter(service__desc_us__icontains = out_words)) RequestConfig(request, paginate={'per_page': 10}).configure(table) RequestConfig(request).configure(table) else: table = PriceTable(Price.objects.all()) RequestConfig(request).configure(table) return render(request, 'results.html', {'table': table}) Here is how I tried in model.py. class Hospital(models.Model): """Model representing Hospitals.""" hid = models.CharField(max_length = 8, null=True) name = models.CharField(max_length=200, primary_key=True) hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular hospital in database') address = models.CharField(max_length = 200, null = True) class Meta: ordering = ['hopid'] #here is where i tried to update it def save(self, *args, **kwargs): self.name = self.name.title() return super(Hospital, self).save(*args, **kwargs) def __str__(self): """String for representing the Model object.""" return f'{self.name} ({self.address})' -
DJANGO - Is it possible to pass arguments to settings through manage.py?
Is it possible to pass arguments to settings through manage.py? I need to pass some arguments to start a server with environment setup. And I think it would be interesting to pass arguments to the settings. Would anyone have another idea? Thank you very much. #python manage.py runserver var=local -
Sending parameters as a list of integer in Django
I'm trying to solve a problem whereby i wanna send multiple doc_id in a body of my headers to be able to create multiple documents on the file objects. However the doc_id is an object instance which throwing an error. So First thing I'm doing is to check if the required documents are more than one, then I'll need to pass a list of doc_id to be able to create the documents.This works when the parameter doc_id is a simple integer, the response is running, i wanna figure out instead of sending one doc_id , how to send multiple doc_id. def create_required_document(self, request, params={}, *args, **kwargs): """ Service that takes a pdf, or a series of images, and creates a pdf file stored against documents required for the claim :param request: the http request :param params: list of params sent by the client machine, including deceased_id, req_doc to modify and the file data. :param args: :param kwargs: :return: The current req_doc status list """ from funeral.models import Deceased, RequiredDocument from funeral.serializers import DocumentType, DocumentTypeSerializer response = dict() logger.debug('%s' % params) files = dict() had_declined = 0 generate_pdf = True b64 = False for key in params.keys(): if 'file_' in key: … -
Django - How to pass a value from a view to a form
I am trying to pass a primary key pk from a view to a form. However I am currently receiving a key error for the value pk. I believe the issue is with the line form = ShowFloorMapForm(pk) as kwargs.pop('pk') returns nothing. Any suggestions are appreciated. Views class DisplayMapView(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): form = ShowFloorMapForm(request.POST) if form.is_valid(): return HttpResponse("valid") else: return HttpResponse("invalid") def get(self, request, pk, *args, **kwargs): building = Building.objects.filter(building_id=pk)[0] form = ShowFloorMapForm(pk) return render(request, 'map.html', {'name':building.name, 'form':form}) Forms class ShowFloorMapForm(forms.Form): map = forms.ModelMultipleChoiceField(queryset = Map.objects.all()) def __init__(self,*args,**kwargs): self.pk = kwargs.pop('pk') super(ShowFloorMapForm, self).__init__(*args,**kwargs) self.fields['map'].queryset = Map.objects.filter(building_id=self.pk)